package com.lzy.websocket.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lzy.websocket.bean.User;
import com.lzy.websocket.service.UserService;

@Controller
public class HomeController {
	
	@Autowired
	private UserService userService;
	
	/**
	 * 获取登录页面
	 * @return
	 */
	@RequestMapping(value = "/",method = RequestMethod.GET)
	public String getIndex() {
		return "login";
	}
	
	/**
	 * 处理登录操作
	 * @param userName
	 * @param password
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/login",method = RequestMethod.POST)
	@ResponseBody
	public String processLogin(String userName,String password,HttpSession session) {
		if(password.equals(userService.getPasswordByName(userName))) {
			User user = new User();
			user.setUserName(userName);
			user.setPassword(password);
			session.setAttribute("user", user);
			return "true";
		}else {
			return "false";
		}
	}
	
	@RequestMapping(value = "/list",method = RequestMethod.GET)
	public String getList(HttpSession session) {
		User user = (User) session.getAttribute("user");
		if(user==null) {
			return "redirect:/";
		}else {
			List<User> list = userService.getUsers(user.getUserName());
			session.setAttribute("userList", list);
			return "list";
		}
	}
}
